package es.deusto.pfc.garuda.server.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.Charset;

import es.deusto.pfc.garuda.server.ClientManager;
import es.deusto.pfc.garuda.server.net.command.Login;
import es.deusto.pfc.garuda.server.net.command.OpCode;

public class NetWorkerThread implements Runnable
{
	private static final Charset UTF8 = Charset.forName("UTF-8");
	private DatagramSocket listeningSocket;
	private ClientManager clientManager;
	private DatagramPacket packet;
	
	public NetWorkerThread(DatagramSocket listeningSocket, ClientManager clientManager, DatagramPacket packet)
	{
		super();
		this.listeningSocket = listeningSocket;
		this.clientManager = clientManager;
		this.packet = packet;
	}

	@Override
	public void run()
	{
		String[] parameters = new String(packet.getData(), UTF8).split(";");
		try
		{
			OpCode opcode = OpCode.valueOf(parameters[0]);
			switch (opcode)
			{
			case LOGIN:
				new Login(clientManager, parameters).execute();
				break;
			default:
				
			}
		}
		catch (IllegalArgumentException e)
		{
			try
			{
				listeningSocket.send(new DatagramPacket(packet.getData(), Net.MTU, InetAddress.getLocalHost(), packet.getPort()));
			}
			catch (IOException e1)
			{
				e1.printStackTrace();
			}
		}
	}
}
